export class Fill {

  onBegin({x: offsetX, y: offsetY}) {
    let {x, y} = this.global.checkXYPX({x: offsetX, y: offsetY});
    const ctx = this.ctx;
    const [fill_r, fill_g, fill_b, fill_a] = this.global.getRgbaFromColor();
    let stack = [[x, y]];
    let c_width = this.canvas.width;
    let c_height = this.canvas.height;
    let id = ctx.getImageData(0, 0, c_width, c_height);
    let pixel_pos = (y * c_width + x) * 4;
    let start_r = id.data[pixel_pos + 0];
    let start_g = id.data[pixel_pos + 1];
    let start_b = id.data[pixel_pos + 2];
    let start_a = id.data[pixel_pos + 3];

    if (
      fill_r === start_r &&
      fill_g === start_g &&
      fill_b === start_b &&
      fill_a === start_a
    ) {
      return;
    }

    while (stack.length) {
      let new_pos, x, y, reach_left, reach_right;
      new_pos = stack.pop();
      x = new_pos[0];
      y = new_pos[1];

      pixel_pos = (y * c_width + x) * 4;
      // 向上查询y的边界
      while (matches_start_color(pixel_pos)) {
        y--;
        pixel_pos = (y * c_width + x) * 4;
      }
      reach_left = false;
      reach_right = false;
      while (true) {
        y++;
        pixel_pos = (y * c_width + x) * 4;

        // y不超出界限 且 当前点位在填充区域内
        if (!(y < c_height && matches_start_color(pixel_pos))) {
          break;
        }

        // 填充当前点位
        color_pixel(pixel_pos);

        if (x > 0) {
          // x左边一个点是否在填充区域内
          if (matches_start_color(pixel_pos - 4)) {
            if (!reach_left) {
              stack.push([x - 1, y]);
              reach_left = true;
            }
          } else if (reach_left) {
            reach_left = false;
          }
        }

        if (x < c_width - 1) {
          if (matches_start_color(pixel_pos + 4)) {
            if (!reach_right) {
              stack.push([x + 1, y]);
              reach_right = true;
            }
          } else if (reach_right) {
            reach_right = false;
          }
        }

        pixel_pos += c_width * 4;
      }
    }
    ctx.putImageData(id, 0, 0);

    // 当前像素是否在填充范围：rgba对比
    function matches_start_color(pixel_pos) {
      // 废弃，防止毛边
      let r = (
        id.data[pixel_pos + 0] === start_r &&
        id.data[pixel_pos + 1] === start_g &&
        id.data[pixel_pos + 2] === start_b &&
        id.data[pixel_pos + 3] === start_a
      );
      return r;
      // todo 计算颜色相似度（需要更好的办法）
      // const r3 = (id.data[pixel_pos+0] - start_r) / 256;
      // const g3 = (id.data[pixel_pos+1] - start_g) / 256;
      // const b3 = (id.data[pixel_pos+2] - start_b) / 256;
      // const diff = Math.sqrt(r3 * r3 + g3 * g3 + b3 * b3);
      // return diff <= 0.9;
    }

    // 修改当前像素的颜色：rgba赋值
    function color_pixel(pixel_pos) {
      id.data[pixel_pos + 0] = fill_r;
      id.data[pixel_pos + 1] = fill_g;
      id.data[pixel_pos + 2] = fill_b;
      id.data[pixel_pos + 3] = fill_a;
    }
  }
}